using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;

//(c) 2011 VDZ
//made for Ludum Dare 22
//
//Licensed under Creative Commons Attribution-NonCommercial 3.0 Unported (CC BY-NC 3.0) 
//
//You are free:
//# to Share — to copy, distribute and transmit the work
//# to Remix — to adapt the work 
//
//Under the following conditions:
//# Attribution — You must attribute the work in the manner specified by the author or licensor
//      (but not in any way that suggests that they endorse you or your use of the work).
//# Noncommercial — You may not use this work for commercial purposes. 
//
//With the understanding that: 
//# Waiver — Any of the above conditions can be waived if you get permission from the copyright holder. 
//# Public Domain — Where the work or any of its elements is in the public domain under applicable law,
//      that status is in no way affected by the license. 
//# Other Rights — In no way are any of the following rights affected by the license:
//  * Your fair dealing or fair use rights, or other applicable copyright exceptions and limitations;
//  * The author's moral rights;
//  * Rights other persons may have either in the work itself or in how the work is used, such as publicity
//      or privacy rights.

public partial class UnityMain : MonoBehaviour, IGUI {
    public enum MenuMode
    {
        None,
        Main,
        GoToSleep,
        Item,
        Anime,
        Manga,
        Game,
        Shop,
        Status
    }
    
    //Constants
    public const float SIDE_BUTTON_X = 77.5f;

    string currency = "Y";
    MenuMode mode;
    public int log_display_lines = 10;
    public float linedelay = 1f;
    public float linedelayleft = 0f;
    Item.ItemType filterType;

    public bool ready = false;
    public bool allowaction = false;
    public bool backlogempty = true;
    int selectedItem = -1;
    public List<string> log;
    public List<string> backlog;
    public List<string> delayedMessages;
    public List<Item> showitems;
    public static MessageBox messageBox = null;
    Vector2 logScrollPosition;
    Vector2 itemScrollPosition;

    public Texture2D frontPicture;
    public Texture2D backPicture;

    AudioClip backgroundSound;
    AudioSource backgroundChannel;
    bool mute = false;
    string currentsound = "";

    //Stats
    public int lcash = 0;
    public int lday = 0;
    public int ldepression = 0;
    public int lcourage = 0;
    public int lsocial = 0;
    public int lhope = 0;
    public int lhealth = 0;

	// Use this for initialization
	void Start () {
        ready = false;

        InitializeStyles();
        logScrollPosition = new Vector2(0f, 0f);
        itemScrollPosition = new Vector2(0f, 0f);

        filterType = Item.ItemType.Food;

        frontPicture = (Texture2D)Resources.Load("general2");
        backPicture = (Texture2D)Resources.Load("general2back");

        backgroundChannel = (AudioSource)Camera.main.gameObject.AddComponent("AudioSource");
        ChangeSound2("BackgroundNoisePassive");
        
        log = new List<string>();
        backlog = new List<string>();
        delayedMessages = new List<string>();
        showitems = new List<Item>();
        GameMain.gui = this;
        GameMain.Initialize();
        ReturnToMain();
        ready = true;
        GameMain.day = 1;

        //////////DEBUG SHIT////////

        //////////////////////////

        UpdateStats();
        GameMain.StartDay();
	}
	
	// Update is called once per frame
	void Update () {
        if (backlog.Count > 0 && messageBox == null)
        {
            backlogempty = false;
            linedelayleft -= Time.deltaTime;
            if (linedelayleft <= 0)
            {
                string[] secretcommands = backlog[0].Split(new string[] { "`" }, StringSplitOptions.None);

                if (secretcommands.Length > 1)
                {
                    if (secretcommands.Length == 2)
                    {
                        switch (secretcommands[1])
                        {
                            case "day": lday = GameMain.day; break;
                            case "cash": lcash = GameMain.cash; break;
                            case "depression": ldepression = GameMain.depression; break;
                            case "courage": lcourage = GameMain.courage; break;
                            case "social": lsocial = GameMain.social; break;
                            case "hope": lhope = GameMain.hope; break;
                            case "health": lhealth = GameMain.health; break;
                            case "messagebox":
                                {
                                    messageBox = new MessageBox(delayedMessages[0]);
                                    delayedMessages.Remove(delayedMessages[0]);
                                    backlog.Remove(backlog[0]);
                                    linedelayleft = linedelay;
                                    if (backlog.Count == 0)
                                    {
                                        backlogempty = true;
                                        UpdateStats();
                                    }
                                    return;
                                }
                            case "endbox":
                                {
                                    messageBox = new MessageBox(delayedMessages[0], delayedMessages[1], true);
                                    //delayedMessages.Remove(delayedMessages[0]);
                                    //delayedMessages.Remove(delayedMessages[0]);
                                    //backlog.Remove(backlog[0]);
                                    //backlog.Remove(backlog[0]);
                                    linedelayleft = linedelay;
                                    if (backlog.Count == 0)
                                    {
                                        backlogempty = true;
                                        UpdateStats();
                                    }
                                    return;
                                }
                            case "picture":
                                {
                                    ChangePicture2(delayedMessages[0]);
                                    delayedMessages.Remove(delayedMessages[0]);
                                    backlog.Remove(backlog[0]);
                                    linedelayleft = 0.01f;
                                    if (backlog.Count == 0)
                                    {
                                        backlogempty = true;
                                        UpdateStats();
                                    }
                                    return;
                                }
                            case "bgsound":
                                {
                                    ChangeSound2(delayedMessages[0]);
                                    delayedMessages.Remove(delayedMessages[0]);
                                    backlog.Remove(backlog[0]);
                                    linedelayleft = 0.01f;
                                    if (backlog.Count == 0)
                                    {
                                        backlogempty = true;
                                        UpdateStats();
                                    }
                                    return;
                                }
                            case "delay":
                                {
                                    backlog.Remove(backlog[0]);
                                    linedelayleft = 4f;
                                    if (backlog.Count == 0)
                                    {
                                        backlogempty = true;
                                        UpdateStats();
                                    }
                                    return;
                                }
                        }
                    }
                    else
                    {
                        int amount = Convert.ToInt32(secretcommands[2]);
                        switch(secretcommands[1])
                        {
                            case "day": lday += amount; break;
                            case "cash": lcash += amount; break;
                            case "depression": ldepression += amount; break;
                            case "courage": lcourage += amount; break;
                            case "social": lsocial += amount; break;
                            case "hope": lhope += amount; break;
                            case "health": lhealth += amount; break;
                        }
                    }
                }

                log.Add(backlog[0]);
                backlog.Remove(backlog[0]);

                linedelayleft = linedelay;
            }
            if (backlog.Count == 0)
            {
                backlogempty = true;
                UpdateStats();
            }
        }
	}

    public void UpdateStats()
    {
        lday = GameMain.day;
        lcash = GameMain.cash;
        ldepression = GameMain.depression;
        lcourage = GameMain.courage;
        lsocial = GameMain.social;
        lhope = GameMain.hope;
        lhealth = GameMain.health;
    }

    public void AllowAction()
    {
        ChangeSound("BackgroundNoiseActive");
        GMsg("<Please choose an action.>");
        allowaction = true;
    }

    public void EndTurn()
    {
        ChangePicture("general");
        ChangeSound("BackgroundNoisePassive");
        GMsg("The day has ended.");
        allowaction = false;
        mode = MenuMode.GoToSleep;
    }

    public void EndGame(GameMain.EndingFlag ending)
    {
        ChangeSound("Silence");
        EndGame2(ending);
    }

    public void EndGame2(GameMain.EndingFlag ending)
    {
        Camera.main.backgroundColor = Color.black;
        string story = "";
        switch (ending)
        {
            case GameMain.EndingFlag.DepressionEnd:
                delayedMessages.Add("Goodbye, cruel world.");
                story =
                    "You have suffered for long enough. You suffer every day, yet you keep on living. " +
                    "Enough. If there's such an easy way out, why do you keep struggling? Society never " +
                    "wanted you anyways. You were always alone in this world. Nobody is going to miss you.\n\n" +
                    "Yet, tears roll down your cheeks as you put your head into the noose. Could life really have " +
                    "been different? Would it really have been possible for you to be happy?\n\n" +
                    "Well...none of that matters now. This is the end.\n\n" +
                    "Goodbye, cruel world...";
                break;
            case GameMain.EndingFlag.HealthEnd:
                delayedMessages.Add("I can't...move...anymore...");
                story =
                    "You feel terrible. Dizzy, nauseous, a splitting headache, and your entire body aches. " +
                    "You try to get up, but you can barely even move your arms and legs. Coughing to the point " +
                    "where you almost suffocate, you realize you should take better care of yourself.\n\n" +
                    "But you can't even get up anymore. And despite the pain, you're starting to feel sleepy. " +
                    "It couldn't be...that it's already...too late...?\n\n" +
                    "As you think that, you slowly lose consciousness...";
                break;
            case GameMain.EndingFlag.RentEnd:
                delayedMessages.Add("When life collapses");
                story =
                    "You read the letter again, and again, and again. But its contents do not change. " +
                    "You, who cannot even go outside without having a panic attack, will be homeless by " +
                    "the end of the week. Your home, the only safe place in this merciless world, will be " +
                    "taken from you.\n\n" +
                    "That's where it has to end. There is nothing left in your life. " +
                    "Your life was already incredibly cruel, and it will only " +
                    "get worse from here on. If that is how life will be...\n\n" +
                    "...then you would much prefer death.";
                break;
            case GameMain.EndingFlag.SocietyEnd:
                Camera.main.backgroundColor = Color.white;
                delayedMessages.Add("A new life");
                story =
                    "You step outside. You walk around in the open. You interact with people on the street. " +
                    "You buy from store clerks without any trouble. And then, at some point, you start to notice.\n\n" +
                    "Only a short time ago, you were unable to even go outside. Yet here you are, freely walking " +
                    "through crowded streets. Talking to strangers. Free to go wherever you want to go without fear " +
                    "of humiliation.\n\n" +
                    "Naturally, this life is still far from perfect. But you've overcome problems others couldn't " +
                    "even imagine. No matter what problems you will face in the future, you will overcome them.\n\n" +
                    "Step by step, you will overcome all obstacles to live the life you want to live, go where you " +
                    "want to go, and do what you want to do. The future is looking bright.";
                break;
        }
        delayedMessages.Add(story + "\n\n(Play time: " + GameMain.day + " days)");
        GMsg("`delay");
        GMsg("`endbox");
    }

    public void GMsg(string message)
    {
        backlog.Add(message);
    }

    public void ChangePicture(string name)
    {
        delayedMessages.Add(name);
        GMsg("`picture");
    }

    public void ChangePicture2(string name)
    {
        int variations = -1;
        switch (name)
        {
            case "anime": variations = 5; break;
            case "board": variations = 5; break;
            case "game": variations = 5; break;
            case "general": variations = 5; break;
            case "manga": variations = 5; break;
            case "mmo": variations = 5; break;
            case "welfare": variations = 3; break;
            case "work": variations = 5; break;
            case "shopanime": variations = 0; break;
            case "shopfood": variations = 0; break;
            case "shopgames": variations = 0; break;
            case "shopmanga": variations = 0; break;
            case "outside": variations = 0; break;
        }

        if (variations == -1) return;

        string fgpic = name;
        if (variations > 0)
        {
            int random = new System.Random().Next(variations) + 1;
            fgpic += random; //Add random number in range to picture name
        }
        string bgpic = fgpic + "back";

        
        foregroundStyle_normal.background = (Texture2D)Resources.Load(fgpic);
        foregroundStyle.normal = foregroundStyle_normal;
        backgroundStyle_normal.background = (Texture2D)Resources.Load(bgpic);
        backgroundStyle.normal = backgroundStyle_normal;
    }

    public void ChangeSound(string name)
    {
        delayedMessages.Add(name);
        GMsg("`bgsound");
    }

    public void ChangeSound2(string name)
    {
        currentsound = name;

        if (name == "Silence" || mute)
        {
            backgroundChannel.Stop();
            return;
        }

        if (backgroundSound != null)
        {
            if (backgroundSound.name == name) return;
        }
        try
        {
            backgroundSound = (AudioClip)Resources.Load(name);
            backgroundChannel.clip = backgroundSound;
            backgroundChannel.loop = true;
            backgroundChannel.Play();
        }
        catch (Exception)
        {
            backgroundSound = (AudioClip)Resources.Load("BackgroundNoisePassive");
            backgroundChannel.clip = backgroundSound;
            backgroundChannel.loop = true;
            backgroundChannel.Play();
        }
    }

    //================================
    //==========FEEDBACK==============
    //================================
    public void Msg(string message)
    {
        GMsg(message);
    }

    public void ItemFeedback(Item item)
    {
        if (item.type == Item.ItemType.Food) return; //Is handled only at start of day, own function
        ChangeSound("BackgroundNoisePassive");
        switch (item.type)
        {
            case Item.ItemType.Anime:
                ChangePicture("anime");
                GMsg("You watch " + item.name + ".");
                break;
            case Item.ItemType.Manga:
                ChangePicture("manga");
                GMsg("You read " + item.name + ".");
                break;
            case Item.ItemType.Game:
                ChangePicture("game");
                if (item.usesLeft > 0)
                {
                    GMsg("You play " + item.name + ".");
                }
                else GMsg("You finish " + item.name + ".");
                break;
        }
        GMsg("`delay");
    }

    public void DayFeedback(int day)
    {
        ChangeSound("BackgroundNoisePassive");
        ChangePicture("general");
        GMsg("Day " + day + " has started.`day");
    }

    public void CashFeedback(int amount)
    {
        if (amount != 0)
        {
            if (amount < 0)
            {
                GMsg("You spend " + currency + Math.Abs(amount) + ".`cash");
            }
            else
            {
                GMsg("You gain " + currency + amount + "!`cash");
            }
        }
    }

    public void DepressionFeedback(int amount)
    {
        if (amount != 0)
        {
            if (amount > 0)
            {
                GMsg("Your depression increases by " + amount + ".`depression");
            }
            else
            {
                GMsg("Your depression decreases by " + Math.Abs(amount) + ".`depression");
            }
        }
    }

    public void CourageFeedback(int amount)
    {
        if (amount != 0)
        {
            if (amount > 0)
            {
                GMsg("You gain " + amount + " courage.`courage");
            }
            else
            {
                GMsg("You lose " + Math.Abs(amount) + " courage.`courage");
            }
        }
    }

    public void SocialFeedback(int amount)
    {
        if (amount != 0)
        {
            if (amount > 0)
            {
                GMsg("You gain " + amount + " social contact.`social");
            }
            else
            {
                GMsg("You lose " + Math.Abs(amount) + " social contact.`social");
            }
        }
    }

    public void HopeFeedback(int amount)
    {
        if (amount != 0)
        {
            if (amount > 0)
            {
                GMsg("You gain " + amount + " hope.`hope");
            }
            else
            {
                GMsg("You lose " + Math.Abs(amount) + " hope.`hope");
            }
        }
    }

    public void HealthFeedback(int amount)
    {
        if (amount != 0)
        {
            if (amount > 0)
            {
                GMsg("Your health increases by " + amount + ".`health");
            }
            else
            {
                GMsg("Your health decreases by " + Math.Abs(amount) + ".`health");
            }
        }
    }

    public void ParentFeedback(int amount)
    {
        if (amount != 0)
        {
            GMsg("You receive " + currency + amount + " from your parents.`cash`" + amount);
        }
    }

    public void WelfareFeedback(int amount)
    {
        if (amount != 0)
        {
            GMsg("You receive " + currency + amount + " in welfare.`cash`" + amount);
        }
    }

    public void MMOSubscriptionFeedback(int amount)
    {
        if (amount != 0)
        {
            GMsg("You pay " + currency + amount + " for your MMO subscription.`cash`" + -amount);
        }
    }

    public void RentFeedback(int amount)
    {
        if (amount != 0)
        {
            GMsg("You pay " + currency + amount + " in rent.`cash`" + -amount);
        }
    }

    public void IllnessFeedback(int amount)
    {
        GMsg("You are unable to do anything today due to illness.");
    }

    public void FoodFeedback(Item item)
    {
        GMsg("You eat your " + item.name + ".");
    }

    public void FoodFailedFeedback()
    {
        GMsg("You don't have anything to eat today!`health");
    }

    public void FoodFinishFeedback()
    {
        bool foodleft = false;
        for (int i = 0; i < GameMain.items.Count; i++)
        {
            if (GameMain.items[i].type == Item.ItemType.Food)
            {
                foodleft = true;
                break;
            }
        }
        if (!foodleft)
        {
            delayedMessages.Add("That was your last food. It is\n recommended that you buy new food.");
            GMsg("`messagebox"); //hax
        }
    }

    public void BoardFeedback()
    {
        ChangeSound("BackgroundNoiseActive");
        ChangePicture("board");
        GMsg("You spend your day browsing textboards.");
        GMsg("`delay");
    }

    public void MMOFeedback()
    {
        ChangeSound("BackgroundNoiseActive");
        ChangePicture("mmo");
        GMsg("You play MMORPGs all day.");
        GMsg("`delay");
    }

    public void InvoluntaryMMOFeedback()
    {
        ChangeSound("BackgroundNoiseActive");
        ChangePicture("mmo");
        GMsg("You decide to spend today playing that one awesome MMO again.");
        GMsg("`delay");
    }

    public void OutsideFeedback()
    {
        ChangePicture("outside");
        ChangeSound("Silence");
        GMsg("You muster up all of your courage and step outside.");
        GMsg("`delay");
    }

    public void OutsideFinishFeedback()
    {
        if (GameMain.social < 11)
        {
            delayedMessages.Add("That was one of the worst experiences you've ever had in your life.");
        }
        else if (GameMain.social < 21)
        {
            delayedMessages.Add("The outside world was absolutely terrifying.");
        }
        else if (GameMain.social < 31)
        {
            delayedMessages.Add("That was extremely stressful. Fortunately the streets were practically empty.");
        }
        else if (GameMain.social < 41)
        {
            delayedMessages.Add("You managed to spend some time outside by avoiding people.");
        }
        else if (GameMain.social < 51)
        {
            delayedMessages.Add("Walking past people was a scary experience, but fortunately nobody recognized you.");
        }
        else if (GameMain.social < 61)
        {
            delayedMessages.Add("You managed to walk through crowded streets.");
        }
        else if (GameMain.social < 71)
        {
            delayedMessages.Add("You were able to walk around outside, and even answered a question somebody asked you.");
        }
        else if (GameMain.social < 81)
        {
            delayedMessages.Add("You were no longer anxious about walking around in the open.");
        }
        else if (GameMain.social < 91)
        {
            delayedMessages.Add("While outside, you had casual conversations with people.");
        }
        else if (GameMain.social < 96)
        {
            delayedMessages.Add("The outside world...it isn't so bad after all.");
        }
        if (GameMain.social < 96) { GMsg("`messagebox"); }
    }

    public void WorkFeedback()
    {
        ChangeSound("BackgroundNoiseActive");
        ChangePicture("work");
        GMsg("You spend all day doing work on the internet for money.");
        GMsg("`delay");
    }

    public void WelfareApplyFeedback()
    {
        ChangeSound("BackgroundNoisePassive");
        ChangePicture("welfare");
        GMsg("You apply for welfare money.");
        GMsg("`delay");
    }

    public void WelfareChangeFeedback(int amount)
    {
        if (amount == 0)
        {
            GMsg("However, your application was refused.");
        }
        else if (amount > 0)
        {
            GMsg("You will be granted an additional " + currency + amount + " per week in welfare!");
        }
        else if (amount < 0)
        {
            delayedMessages.Add("The government has decided to lower your welfare income by " + currency + Math.Abs(amount) + 
                "to " + currency + GameMain.welfare_income + ".");
            GMsg("`messagebox");
        }
    }

    public void WelfareFailFeedback()
    {
        ChangeSound("BackgroundNoisePassive");
        ChangePicture("welfare");
        GMsg("You spend all day preparing your application, but in the end you don't have the courage to send it.");
        GMsg("`delay");
    }

    public void WorkFinishFeedback(int amount)
    {
        if (amount == 0)
        {
            GMsg("You were unable to find internet work today.");
        }
        else
        {
            GMsg("You managed to earn " + currency + amount + " today.`cash");
        }
    }

    public void MMOFailFeedback()
    {
        delayedMessages.Add("Your account is blocked until you pay your unpaid subscription fees.");
        GMsg("`messagebox");
        ReturnToMain();
    }

    public void MMOCantFeedback()
    {
        GMsg("You strongly regret being unable to play your MMO.");
    }

    public void ParentDropFeedback(int amount)
    {
        if (amount != 0 && GameMain.parent_income != 0)
        {
            if (GameMain.parent_income - amount > 0)
            {
                delayedMessages.Add("Due to financial problems, your parents have decided to send you " + currency +
                    Math.Abs(amount) + " less per week. You now get " + currency + GameMain.parent_income + " per week.");
                GMsg("`messagebox");
            }
            else
            {
                delayedMessages.Add("Your parents are in serious financial trouble, and they can no longer support you. " +
                    "You will no longer get money from your parents.");
                GMsg("`messagebox");
            }
        }
    }

    public void GetSickFeedback(int duration)
    {
        if (duration < 2)
        {
            delayedMessages.Add("You feel sick.");
            GMsg("`messagebox");
        }
        else if (duration < 3)
        {
            delayedMessages.Add("You feel very sick.");
            GMsg("`messagebox");
        }
        else if (duration < 4)
        {
            delayedMessages.Add("You feel incredibly sick.");
            GMsg("`messagebox");
        }
        else
        {
            delayedMessages.Add("You feel like you're about to die.");
            GMsg("`messagebox");
            //And that's because you are.
        }
    }

    //============================
    //====UNITY GUI SYSTEM======== (the horror)
    //============================

    //Okay, absolute pixel values are terrible. Therefore I'm using a system that runs from (0,0) to (99, 74),
    //and converting all values to pixels.
    public const int VIRTUAL_WIDTH = 100;
    public const int VIRTUAL_HEIGHT = 75;

    public static float ConvertX(float x)
    {
        return Convert.ToInt32(((float)(x / (float)VIRTUAL_WIDTH) * (float)Screen.width));
    }

    public static float ConvertY(float y)
    {
        return Convert.ToInt32(((float)(y / (float)VIRTUAL_HEIGHT) * (float)Screen.height));
    }

    void DisplayTitle()
    {
        //Title logo
        GUI.Box(new Rect(ConvertX(30), ConvertY(0), ConvertX(40), ConvertY(10)), (Texture)Resources.Load("title"), pictureStyle);
    }

    void DisplayStats()
    {
        //Display stats
        GUI.Box(new Rect(ConvertX(2.5f), ConvertY(12.5f), ConvertX(20), ConvertY(40)),
            "Day " + lday + "\n\n" +
            "Cash: " + currency + lcash + "\n\n" +
            "Depression: " + ldepression + "\n\n" +
            "Courage: " + lcourage + "\n" +
            "Hope: " + lhope + "\n" +
            "Health: " + lhealth + "\n\n" +
            "Social contact: " + lsocial,
            itemListStyle);
    }

    void DisplayLog()
    {
        //Display log
        string logtext = "";
        //for (int i = log.Count - 1; i > log.Count - log_display_lines; i--)
        for(int i = log.Count - 1; i > -1; i--)
        {
            if (i > -1)
                logtext += log[i].Split(new string[] { "`" }, StringSplitOptions.None)[0] + "\n";
        }
        logScrollPosition = GUI.BeginScrollView(new Rect(ConvertX(25), ConvertY(55), ConvertX(50), ConvertY(19.5f)), logScrollPosition,
            new Rect(ConvertX(25), ConvertY(55), ConvertX(47.5f), ConvertY(200)), false, true);

        GUI.TextArea(new Rect(ConvertX(26), ConvertY(55), ConvertX(48), ConvertY(200)), logtext, logStyle);
        GUI.EndScrollView();
    }

    void DisplayItems()
    {
        float correcty = (float)showitems.Count * 7.5f;
        if (correcty < 47.5f) correcty = 47.5f;
        itemScrollPosition = GUI.BeginScrollView(
            new Rect(ConvertX(5), ConvertY(12.5f), ConvertX(65), ConvertY(47.5f)),
            itemScrollPosition,
            new Rect(ConvertX(5), ConvertY(12.5f), ConvertX(62.5f), ConvertY(correcty)), false, true);

        GUI.Box(new Rect(ConvertX(5), ConvertY(12.5f), ConvertX(62.5f), ConvertY(47.5f)), GUIContent.none, itemListStyle);

        for (int i = 0; i < showitems.Count; i++)
        {
            string text = showitems[i].name;
            if (mode == MenuMode.Shop) text += " (" + currency + showitems[i].price + ")";
            if (selectedItem != i)
            {
                if (GUI.Button(new Rect(
                    ConvertX(5f), ConvertY(12.5f + 7.5f * (float)i), ConvertX(62.5f), ConvertY(7.5f)), text,
                    buttonStyle))
                {
                    selectedItem = i;
                }
            }
            else GUI.Button(new Rect(
                  ConvertX(5f), ConvertY(12.5f + 7.5f * (float)i), ConvertX(62.5f), ConvertY(7.5f)), text,
                  selectedButtonStyle);
        }

        GUI.EndScrollView();

        string description = "";

        if (selectedItem > -1)
        {
            Item source = showitems[selectedItem];
            description = source.name + "\n\n";
            if (mode == MenuMode.Shop)
            {
                description += "Price: " + currency + source.price + "\n\n";
            }
            description += source.description;
        }

        GUI.Box(new Rect(ConvertX(72.5f), ConvertY(12.5f), ConvertX(27.5f), ConvertY(47.5f)),
            description, itemListStyle);
    }

    void DisplayUseButton(string text)
    {
        if (GUI.Button(new Rect(ConvertX(20), ConvertY(65), ConvertX(20), ConvertY(5)), text, buttonStyle)) { UseItemButton(); }
    }

    void DisplayCancelButton()
    {
        if (GUI.Button(new Rect(ConvertX(60), ConvertY(65), ConvertX(20), ConvertY(5)), "Back", buttonStyle)) { ReturnToMain(); }
    }

    void DisplayBuyButton()
    {
        if (GUI.Button(new Rect(ConvertX(20), ConvertY(65), ConvertX(20), ConvertY(5)), "Buy", buttonStyle))
        {
            if (GameMain.BuyItem(showitems[selectedItem]))
            {
                messageBox = new MessageBox("Bought " + showitems[selectedItem].name + "!");
                GMsg("Bought " + showitems[selectedItem].name + " (" + currency + showitems[selectedItem].price + ").`cash");
                FilterShopItems(filterType);
            }
            else
            {
                messageBox = new MessageBox("You don't have enough money to buy that!");
            }
        }
    }

    void FilterShopItems(Item.ItemType type)
    {
        filterType = type;
        selectedItem = -1;
        List<Item> thatlist;
        switch (type)
        {
            case Item.ItemType.Anime: thatlist = GameMain.anime; break;
            case Item.ItemType.Manga: thatlist = GameMain.manga; break;
            case Item.ItemType.Game: thatlist = GameMain.games; break;
            default: thatlist = GameMain.food; break;
        }

        showitems = new List<Item>();

        for (int i = 0; i < thatlist.Count; i++)
        {
            if (!thatlist[i].soldOut && thatlist[i].Released()) showitems.Add(thatlist[i]);
        }

        ChangeSound("BackgroundNoisePassive");
        switch (type)
        {
            case Item.ItemType.Anime: ChangePicture("shopanime"); break;
            case Item.ItemType.Manga: ChangePicture("shopmanga"); break;
            case Item.ItemType.Game: ChangePicture("shopgames"); break;
            case Item.ItemType.Food: ChangePicture("shopfood"); break;
        }
    }

    void OnGUI()
    {
        if (!ready) return;

        if (GameMain.endingFlag != GameMain.EndingFlag.None)
        {
            if (messageBox != null)
            {
                if (messageBox.ending == true)
                {
                    messageBox.Display();
                    return;
                }
            }
        }

        GUI.Box(new Rect(ConvertX(0), ConvertY(0), ConvertX(100), ConvertY(75)), "", backgroundStyle);
        if (mode == MenuMode.Main || mode == MenuMode.GoToSleep) //Foreground picture
        {
            GUI.Box(new Rect(ConvertX(25), ConvertY(16.25f), ConvertX(50), ConvertY(37.5f)), "", foregroundStyle);
        }

        switch (mode)
        {
            case MenuMode.None:
                {
                    break;
                }

                //-------------------Main menu-----------
            case MenuMode.Main:
                {
                    DisplayTitle();
                    DisplayStats();
                    DisplayLog();

                    if (messageBox != null)
                    {
                        messageBox.Display();
                        return;
                    }
                    
                    //Action buttons
                    if (allowaction && backlogempty)
                    {
                        if (GUI.Button(new Rect(ConvertX(SIDE_BUTTON_X), ConvertY(10), ConvertX(20), ConvertY(5)),
                            "Buy things online", buttonStyle)) { BuyButton(); }
                        if (GUI.Button(new Rect(ConvertX(SIDE_BUTTON_X), ConvertY(15), ConvertX(20), ConvertY(5)),
                            "Browse textboards", buttonStyle)) { BrowseButton(); }
                        if (GUI.Button(new Rect(ConvertX(SIDE_BUTTON_X), ConvertY(20), ConvertX(20), ConvertY(5)),
                            "Watch anime", buttonStyle)) { AnimeButton(); }
                        if (GUI.Button(new Rect(ConvertX(SIDE_BUTTON_X), ConvertY(25), ConvertX(20), ConvertY(5)),
                            "Read manga", buttonStyle)) { MangaButton(); }
                        if (GUI.Button(new Rect(ConvertX(SIDE_BUTTON_X), ConvertY(30), ConvertX(20), ConvertY(5)),
                            "Play games", buttonStyle)) { GameButton(); }
                        if (GUI.Button(new Rect(ConvertX(SIDE_BUTTON_X), ConvertY(35), ConvertX(20), ConvertY(5)),
                            "Play MMORPGs", buttonStyle)) { MMOButton(); }
                        if (GUI.Button(new Rect(ConvertX(SIDE_BUTTON_X), ConvertY(40), ConvertX(20), ConvertY(5)),
                            "Go outside", buttonStyle)) { OutsideButton(); }
                        if (GUI.Button(new Rect(ConvertX(SIDE_BUTTON_X), ConvertY(45), ConvertX(20), ConvertY(5)),
                            "Do internet work", buttonStyle)) { WorkButton(); }
                        if (GUI.Button(new Rect(ConvertX(SIDE_BUTTON_X), ConvertY(50), ConvertX(20), ConvertY(5)),
                            "Apply for welfare", buttonStyle)) { WelfareButton(); }
                        if (GUI.Button(new Rect(ConvertX(SIDE_BUTTON_X), ConvertY(55), ConvertX(20), ConvertY(5)),
                            "View items", buttonStyle)) { ItemButton(); }
                        //Removed due to time limit
                        //if (GUI.Button(new Rect(ConvertX(SIDE_BUTTON_X), ConvertY(60), ConvertX(20), ConvertY(5)),
                        //    "View status", buttonStyle)) { StatusButton(); }
                        string text = "Mute";
                        if (mute) text = "Unmute";
                        if (GUI.Button(new Rect(ConvertX(90), ConvertY(70), ConvertX(7.5f), ConvertY(2.5f)), text, buttonStyle))
                        {
                            MuteButton();
                        }
                    }
                    break;
                }

                //-----------Go to sleep-------------
            case MenuMode.GoToSleep:
                {
                    DisplayTitle();
                    DisplayStats();
                    DisplayLog();

                    if (messageBox != null)
                    {
                        messageBox.Display();
                        return;
                    }

                    //Action button
                    if (backlogempty)
                    {
                        if (GUI.Button(new Rect(ConvertX(SIDE_BUTTON_X), ConvertY(10), ConvertX(20), ConvertY(5)),
                            "Go to sleep", buttonStyle)) { mode = MenuMode.Main; GameMain.EndDay(); }
                    }
                    break;
                }
                //-----------Item list-------------
            case MenuMode.Item:
                {
                    DisplayItems();

                    if (messageBox != null)
                    {
                        messageBox.Display();
                        return;
                    }

                    if (GUI.Button(new Rect(ConvertX(40), ConvertY(65), ConvertX(20), ConvertY(5)), "Back",
                        buttonStyle)) { ReturnToMain(); }
                    break;
                }
                //----------Anime/manga/games------
            case MenuMode.Anime:
                {
                    DisplayItems();

                    if (messageBox != null)
                    {
                        messageBox.Display();
                        return;
                    }

                    DisplayUseButton("Watch");
                    DisplayCancelButton();
                    break;
                }
            case MenuMode.Manga:
                {
                    DisplayItems();

                    if (messageBox != null)
                    {
                        messageBox.Display();
                        return;
                    }

                    DisplayUseButton("Read");
                    DisplayCancelButton();
                    break;
                }
            case MenuMode.Game:
                {
                    DisplayItems();

                    if (messageBox != null)
                    {
                        messageBox.Display();
                        return;
                    }

                    DisplayUseButton("Play");
                    DisplayCancelButton();
                    break;
                }
                //----------Shop--------
            case MenuMode.Shop:
                {
                    if (messageBox == null) //FIXME: Should be possible to use both at the same time
                    {
                        DisplayItems();
                    }
                    //Display tabs
                    if (filterType == Item.ItemType.Food)
                        GUI.Button(new Rect(ConvertX(5), ConvertY(5), ConvertX(20), ConvertY(5)),
                            "Food", selectedButtonStyle);
                    else if (GUI.Button(new Rect(ConvertX(5), ConvertY(5), ConvertX(20), ConvertY(5)),
                            "Food", buttonStyle)) { FilterShopItems(Item.ItemType.Food); }
                    if (filterType == Item.ItemType.Anime)
                        GUI.Button(new Rect(ConvertX(25), ConvertY(5), ConvertX(20), ConvertY(5)),
                            "Anime", selectedButtonStyle);
                    else if (GUI.Button(new Rect(ConvertX(25), ConvertY(5), ConvertX(20), ConvertY(5)),
                            "Anime", buttonStyle)) { FilterShopItems(Item.ItemType.Anime); }
                    if (filterType == Item.ItemType.Manga)
                        GUI.Button(new Rect(ConvertX(45), ConvertY(5), ConvertX(20), ConvertY(5)),
                            "Manga", selectedButtonStyle);
                    else if (GUI.Button(new Rect(ConvertX(45), ConvertY(5), ConvertX(20), ConvertY(5)),
                            "Manga", buttonStyle)) { FilterShopItems(Item.ItemType.Manga); }
                    if (filterType == Item.ItemType.Game)
                        GUI.Button(new Rect(ConvertX(65), ConvertY(5), ConvertX(20), ConvertY(5)),
                            "Games", selectedButtonStyle);
                    else if (GUI.Button(new Rect(ConvertX(65), ConvertY(5), ConvertX(20), ConvertY(5)),
                            "Games", buttonStyle)) { FilterShopItems(Item.ItemType.Game); }

                    GUI.TextArea(new Rect(ConvertX(86.25f), ConvertY(5), ConvertX(12.5f), ConvertY(5)),
                        "Cash: " + currency + GameMain.cash, itemListStyle);

                    if (messageBox != null)
                    {
                        messageBox.Display();
                        return;
                    }

                    DisplayBuyButton();
                    DisplayCancelButton();
                    break;
                }

        }
    }

    public void BuyButton()
    {
        FilterShopItems(Item.ItemType.Food);
        mode = MenuMode.Shop;
    }

    public void BrowseButton()
    {
        allowaction = false;
        GameMain.BrowseBoards();
    }

    public void AnimeButton()
    {
        selectedItem = -1;
        showitems = new List<Item>();
        for (int i = 0; i < GameMain.items.Count; i++)
        {
            if (GameMain.items[i].type == Item.ItemType.Anime)
            {
                showitems.Add(GameMain.items[i]);
            }
        }
        mode = MenuMode.Anime;
    }

    public void MangaButton()
    {
        selectedItem = -1;
        showitems = new List<Item>();
        for (int i = 0; i < GameMain.items.Count; i++)
        {
            if (GameMain.items[i].type == Item.ItemType.Manga)
            {
                showitems.Add(GameMain.items[i]);
            }
        }
        mode = MenuMode.Manga;
    }

    public void GameButton()
    {
        selectedItem = -1;
        showitems = new List<Item>();
        for (int i = 0; i < GameMain.items.Count; i++)
        {
            if (GameMain.items[i].type == Item.ItemType.Game)
            {
                showitems.Add(GameMain.items[i]);
            }
        }
        mode = MenuMode.Game;
    }

    public void MMOButton()
    {
        allowaction = false;
        GameMain.PlayMMO();
    }

    public void OutsideButton()
    {
        allowaction = false;
        if (!GameMain.GoOutside())
        {
            messageBox = new MessageBox("You stand in front of your door, but you can't bring up the courage to open it.");
            allowaction = true;
        }

    }

    public void WorkButton()
    {
        allowaction = false;
        GameMain.WorkOnline();
    }

    public void WelfareButton()
    {
        allowaction = false;
        GameMain.ApplyForWelfare();
    }

    public void ItemButton()
    {
        selectedItem = -1;
        showitems = GameMain.items;
        mode = MenuMode.Item;
    }

    public void StatusButton()
    {
        //TODO
    }

    public void MuteButton()
    {
        if (mute)
        {
            mute = false;
            ChangeSound2(currentsound);
        }
        else
        {
            mute = true;
            backgroundChannel.Stop();
            backgroundSound = null;
        }
    }

    public void UseItemButton()
    {
        if (selectedItem > -1)
        {
            mode = MenuMode.Main;
            GameMain.Entertainment(showitems[selectedItem]);
        }
        else messageBox = new MessageBox("Please select an item to use first.");
    }

    public void ReturnToMain() //Returning to the main menu
    {
        ChangePicture("general");
        ChangeSound("BackgroundNoiseActive");
        mode = MenuMode.Main;
        allowaction = true;
    }

}
